# coding=utf-8

import sys
import os
import subprocess
import hashlib
import datetime


# 获得当前时间
def getNowTime():
    now = datetime.datetime.now()
    # 转换为指定的格式:
    nowTime = now.strftime("%Y-%m-%d %H:%M:%S")
    return nowTime

def printNow(str):
    print(getNowTime() + " " + str)
    # sys.stdout.flush()

# printNow(f"time---in-------:, {datetime.datetime.now().timestamp()}")
# printNow(f"{sys.argv}")

exePath = sys.argv[0]
(curPath, fileName) = os.path.split(exePath)
fromPath = sys.argv[2]
targetPath = sys.argv[4]
fromPath = fromPath.replace("/", "\\")
targetPath = targetPath.replace("/", "\\")

cachePath = curPath + "\\compressedTexturesCache\\"
textureType = "picture"
cacheDir = cachePath + textureType

targetFileDir, targetFileName = os.path.split(targetPath)
splitName = targetFileName.split(".")[0]
newPath = targetFileDir + "\\" + splitName + ".astc" 

# 创建缓存目录
if not os.path.exists(cacheDir):
        os.makedirs(cacheDir)
   
time1 = datetime.datetime.now().timestamp()
md5 = hashlib.md5(open(fromPath, "rb").read()).hexdigest()
time2 = datetime.datetime.now().timestamp()
# printNow(f"time---md5-------:, {time2 - time1}")

# printNow(f"cacheDir----------:,{cacheDir}")
# printNow(f"fileName----------:,{fileName}")
# printNow(f"curPath----------:,{curPath}")
# printNow(f"fromPath----------:,{fromPath}")

newCachePath = cacheDir + "\\" + md5 + ".astc"
# printNow(f"newCachePath----------:,{newCachePath}")

time3 = datetime.datetime.now().timestamp()
if not os.path.exists(newCachePath):
    pvrType = sys.argv[12]
    printNow(f"quality1: {pvrType}")
    astcType = '8x8' if pvrType == 'PVRTC1_2,UBN,lRGB' else '4x4'
    printNow(f'astcType1: {astcType}')
    
    # 缓存文件不存在, 压缩此图片
    res = subprocess.call(f'{curPath}\\astcenc-sse2 -cl {fromPath} {newCachePath} {astcType} -medium', shell=True)
    # printNow(f'res-----------: {res}')
    # if res == 0:
    #     # 压缩成功, 根据 MD5 重命名
    #     os.rename(cacheDir + "\\" + fileName.split(".")[0] + ".astc", cacheDir + "\\" + md5 + ".astc")
else:
    printNow("file is alreday now")
time4 = datetime.datetime.now().timestamp()
printNow(f"time---astc-------:, {time4 - time3}")

# printNow(f"newPath----------:, {newPath}")
# 拷贝文件
time5 = datetime.datetime.now().timestamp()
status = subprocess.call("copy" + " " + newCachePath + " " + newPath, shell=True)
if status != 0:
    if status < 0:
        printNow(f"Killed by signal, {status}")
    else:
        printNow(f"Command failed with return code - , {status}")
else:
    printNow("copy success!")
time6 = datetime.datetime.now().timestamp()
printNow(f"time---copy-------:, {time6 - time5}")

# printNow(f"time---out-------:, {datetime.datetime.now().timestamp()}")
